import { loginAPI, getUserInfoAPI } from '@/api/user'
import router, { constantRoutes, resetRouter } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { Message } from 'element-ui'
const state = {
  token: getToken() || null,
  userInfo: {},
  routes: constantRoutes
}

const mutations = {
  setToken(state, token) {
    state.token = token
    // 同步到缓存
    setToken(token)
  },
  removeToken(state) {
    // 删除Vuex的token
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes] // 静态路由 + 动态路由
  }

}

const actions = {
  // 登录
  async login(context, data) {
    const token = await loginAPI(data)
    console.log('token  ----->  ', token)
    context.commit('setToken', token)
    Message.success('登录成功')
    router.push('/')
  },
  // 获取用户资料
  async getUserInfo(context) {
    const user = await getUserInfoAPI()
    console.log('获取用户资料  ----->  ', user)
    context.commit('setUserInfo', user)
    return user
  },
  // 退出登录的action
  logout(context) {
    context.commit('removeToken') // 删除token
    context.commit('setUserInfo', {}) // 设置用户信息为空对象
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true, // 开启命名空间
  state,
  mutations,
  actions
}
